package com.galeno.sql;

import org.apache.flink.api.common.functions.MapFunction;
import org.apache.flink.api.common.typeinfo.Types;
import org.apache.flink.streaming.api.CheckpointingMode;
import org.apache.flink.streaming.api.datastream.DataStream;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.timestamps.BoundedOutOfOrdernessTimestampExtractor;
import org.apache.flink.streaming.api.windowing.time.Time;
import org.apache.flink.table.api.Table;
import org.apache.flink.table.api.bridge.java.StreamTableEnvironment;
import org.apache.flink.types.Row;

import static org.apache.flink.table.api.Expressions.$;
import static org.apache.flink.table.api.Expressions.e;

/**
 * @author galeno
 * @Title:
 * @Description:
 * @date 2021/10/312:19
 */
public class SqlTumbingEventTimeWindow {
    public static void main(String[] args) throws Exception {
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.setParallelism(1);
       // env.enableCheckpointing(10000);

        StreamTableEnvironment tbEnv = StreamTableEnvironment.create(env);

        DataStreamSource<String> lines = env.socketTextStream("galeno01", 9999);
        SingleOutputStreamOperator<Row> rowStream = lines.map(new MapFunction<String, Row>() {
            @Override
            public Row map(String value) throws Exception {
                String[] split = value.split(",");
                return Row.of(Long.parseLong(split[0]), split[1], split[2], Double.parseDouble(split[3]));


            }
        }).returns(Types.ROW(Types.LONG, Types.STRING, Types.STRING, Types.DOUBLE));
        SingleOutputStreamOperator<Row> watermarkRow = rowStream.assignTimestampsAndWatermarks(new BoundedOutOfOrdernessTimestampExtractor<Row>(Time.seconds(0)) {
            @Override
            public long extractTimestamp(Row element) {
                Long ts = (Long) element.getField(0);
                return ts;
            }
        });
        tbEnv.createTemporaryView("t_orders",watermarkRow,$("time")
            ,$("uid")
            ,$("pid")
                ,$("money")
                ,$("etime").rowtime()
        );
        //使用SQL实现按照EventTime划分滚动窗口聚合
        String sql = "SELECT uid, SUM(money) total_money, TUMBLE_START(etime, INTERVAL '10' SECOND) as win_start, " +
                "TUMBLE_END(etime, INTERVAL '10' SECOND) as win_end " +
                "FROM t_orders GROUP BY TUMBLE(etime, INTERVAL '10' SECOND), uid";
        Table table = tbEnv.sqlQuery(sql);
        DataStream<Row> res = tbEnv.toAppendStream(table, Row.class);
        res.print();
        env.execute();


    }
}
